package com.bbyb.operating.examination.handler;

import com.bbyb.operating.examination.model.vo.CommonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author DongZl
 * @description: 全局异常处理
 * @Date 2024-1-10 下午 08:49
 */
@Log4j2
@RestControllerAdvice
@Configuration
public class GlobalExceptionHandler {

//    @ExceptionHandler(value = MethodArgumentNotValidException.class)
//    public CommonResult<String> runtimeException (MethodArgumentNotValidException exception) {
//        log.error("请求异常：[{}]", exception.getMessage(), exception);
//        return CommonResult.error(
//                JSONObject.toJSONString(
//                        exception.getBindingResult().getAllErrors()
//                                .stream()
//                                .map(ObjectError::getDefaultMessage)
//                                .toList()
//                )
//        );
//    }
//
//    @ExceptionHandler(value = IllegalArgumentException.class)
//    public Result<String> illegalArgumentExceptionHandler(IllegalArgumentException exception){
//        log.error("请求异常：[{}]", exception.getMessage(), exception);
//        return Result.error(exception.getMessage());
//    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult<String> handleException(Exception e) {
        log.error("请求异常：[{}]", e.getMessage(), e);
        CommonResult<String> result = new CommonResult<>();
        result.setCode(-1);
        result.setMsg(e.getMessage());
        result.setSuccess(false);
        return result;
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public CommonResult<String> illegalArgumentExceptionHandler(IllegalArgumentException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        CommonResult<String> result = new CommonResult<>();
        result.setCode(-1);
        result.setMsg(exception.getMessage());
        result.setSuccess(false);
        //    }
        return result;
    }

    @ExceptionHandler(value = RuntimeException.class)
    public CommonResult<String> RuntimeException(RuntimeException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        CommonResult<String> result = new CommonResult<>();
        result.setCode(-1);
        result.setMsg(exception.getMessage());
        result.setSuccess(false);
        return result;
    }

}
